using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.Adapters;
using System.Web.UI;
using System.IO;
using System.Text.RegularExpressions;

namespace CewpUriRewriter
{
    /// <summary>
    /// This controladapter converts all Absolute Urls to Relative Urls.
    /// Be aware that with this controladapter enabled no external hyperlinks are possible anymore.
    /// http://blog.mastykarz.nl/inconvenient-content-editor-web-part/
    /// </summary>
    public class CewpRelativeUrlControlAdapter : ControlAdapter
    {
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            StringBuilder sb = new StringBuilder();
            HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
            base.Render(htw);

            // make all URLs relative
            Regex regex = new Regex("((?:href|src)=\")https?://[^/]+([^\"]+\")");
            string output = regex.Replace(sb.ToString(), "$1$2");

            writer.Write(output);
        }
    }
}
